<template>
  <div class="table-container">
    <el-card class="box-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-statistic title="总工单数" :value="totalData.totalNum" group-separator=",">
              <template slot="suffix">
                <i class="el-icon-document" style="color: #f56c6c"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic title="总完成数" :value="totalData.totalFinishNum" group-separator=",">
              <template slot="suffix">
                <i class="el-icon-document-checked" style="color: #67c23a"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic title="本周工单数" :value="totalData.totalWeekNum" group-separator=",">
              <template slot="suffix">
                <i class="el-icon-top" style="color: #f56c6c"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic title="本周完成数" :value="totalData.totalWeekFinishNum" group-separator=",">
              <template slot="suffix">
                <i class="el-icon-s-flag" style="color: #67c23a"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-date-picker
          :picker-options="{ firstDayOfWeek: 1 }"
          v-model="currentWeek"
          type="week"
          format="yyyy 第 WW 周"
          value-format="yyyy-MM-dd"
          placeholder="选择周"
          @change="handleChange"
          :clearable="false"
        />
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd">添加</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <el-select v-model="queryForm.state" placeholder="请选择工单状态">
          <el-option label="全部" :value="''"></el-option>
          <el-option label="未完成" :value="1"></el-option>
          <el-option label="已完成" :value="2"></el-option>
          <el-option label="取消" :value="3"></el-option>
        </el-select>
        <el-form ref="form" :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="queryForm.title" placeholder="费用号/项目名称" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" native-type="submit" type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      :data="list"
      :element-loading-text="elementLoadingText"
      :height="height"
      :row-class-name="tableRowClassName"
      border
    >
      <el-table-column label="序号" show-overflow-tooltip width="95">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="费用号" prop="costNumber" show-overflow-tooltip />
      <el-table-column label="项目名称" prop="projectName" show-overflow-tooltip />
      <el-table-column label="工单内容" prop="workContent" show-overflow-tooltip min-width="220" />
      <el-table-column label="客户需求" prop="isCustomerDemand">
        <template #default="{ row }">
          {{ row.isCustomerDemand == 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="工单下达时间" prop="workOrderIssuanceTime" show-overflow-tooltip min-width="120" />
      <el-table-column label="执行人" prop="executUserName" />
      <el-table-column label="完成情况">
        <template #default="{ row }">
          <el-tag type="success" effect="dark" v-if="row.completionStatus == 2">已完成</el-tag>
          <el-tag type="info" effect="dark" v-else-if="row.completionStatus == 3">取消</el-tag>
          <el-tag type="" effect="dark" v-else>未完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" prop="completionTime" show-overflow-tooltip min-width="120" />
      <el-table-column label="工单等级" prop="levelName" sortable min-width="100" />
      <el-table-column label="未关闭原因" prop="notClosingReason" show-overflow-tooltip min-width="120" />
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
          <el-button type="text" @click="handleFinish(row)">完成</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit ref="edit" @refreshTable="init" />
  </div>
</template>

<script>
  import { getWorkOrderListByDepartId, deleteWorkOrder, finishWorkOrder, getWorkOrderTotalByDepartId } from '@/api/wordOrder'
  import TableEdit from './components/TableEdit'

  export default {
    name: 'one',
    components: {
      TableEdit,
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger',
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        currentWeek: '',
        totalData: {
          totalNum: '',
          totalFinishNum: '',
          totalWeekNum: '',
          totalWeekFinishNum: '',
        },
        imgShow: true,
        list: [],
        imageList: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          departmentId: 1,
          startDate: '',
          endDate: '',
          pageNo: 1,
          pageSize: 20,
          title: '',
          state: '',
        },
        timeOutID: null,
      }
    },
    watch: {
      'queryForm.state'(newValue, oldValue) {
        this.fetchData()
      },
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      const { getMondayAndSundayOfCurrentWeek } = require('@/utils/index')
      const { monday, sunday } = getMondayAndSundayOfCurrentWeek()
      this.currentWeek = monday
      this.queryForm.startDate = monday
      this.queryForm.endDate = sunday
      this.init()
    },
    beforeDestroy() {},
    mounted() {},
    methods: {
      init() {
        this.fetchData()
        this.fetchBarData()
      },
      getNewDay(dateTemp, days) {
        var dateTemp = dateTemp.split('-')
        var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]) //转换为MM-DD-YYYY格式
        var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
        var rDate = new Date(millSeconds)
        var year = rDate.getFullYear()
        var month = rDate.getMonth() + 1
        if (month < 10) month = '0' + month
        var date = rDate.getDate()
        if (date < 10) date = '0' + date
        return year + '-' + month + '-' + date
      },
      handleChange(e) {
        let d = new Date(e)
        d.setDate(d.getDate() - 1)
        let year = d.getFullYear()
        let month = (d.getMonth() + 1).toString().padStart(2, '0')
        let date = d.getDate().toString().padStart(2, '0')
        this.currentWeek = year + '-' + month + '-' + date
        this.queryForm.startDate = this.currentWeek
        this.queryForm.endDate = this.getNewDay(this.currentWeek, 6)
        console.log(123, this.queryForm)
        this.init()
      },
      tableSortChange() {
        const imageList = []
        this.$refs.tableSort.tableData.forEach((item, index) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await deleteWorkOrder({ id: row.id })
          this.$baseMessage(msg, 'success')
          this.init()
        })
      },
      handleFinish(row) {
        this.$baseConfirm('你确定要完成当前项吗', null, async () => {
          const { msg } = await finishWorkOrder({ id: row.id })
          this.$baseMessage(msg, 'success')
          this.init()
        })
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        const { data, total } = await getWorkOrderListByDepartId(this.queryForm)
        this.list = data
        this.total = total
      },
      async fetchBarData() {
        const { data } = await getWorkOrderTotalByDepartId(this.queryForm)
        this.totalData = data
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.completionStatus == 2) {
          return 'success-row'
        } else if (row.completionStatus == 3) {
          return 'info-row'
        }
        return ''
      },
    },
  }
</script>
<style>
  .el-table .info-row {
    background: #f0f0f0;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
